<template>
  <Dialog v-model="dialogVisible" title="批量创建科目" width="1000px">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 批量创建 -->
      <el-tab-pane label="批量创建" name="batch">
        <el-form
          ref="batchFormRef"
          :model="batchForm"
          :rules="batchRules"
          label-width="120px"
          v-loading="formLoading"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="批量创建方式" prop="createMethod">
                <el-radio-group v-model="batchForm.createMethod">
                  <el-radio value="template">使用模板</el-radio>
                  <el-radio value="import">Excel导入</el-radio>
                  <el-radio value="manual">手动创建</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目标职业" prop="professionId">
                <el-select v-model="batchForm.professionId" placeholder="请选择职业">
                  <el-option label="电工" value="1" />
                  <el-option label="焊工" value="2" />
                  <el-option label="车工" value="3" />
                  <el-option label="钳工" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 模板创建 -->
          <div v-if="batchForm.createMethod === 'template'">
            <el-divider content-position="left">选择模板</el-divider>
            <el-form-item label="科目模板" prop="templateId">
              <el-select v-model="batchForm.templateId" placeholder="请选择科目模板" @change="loadTemplate">
                <el-option label="电工标准科目模板" value="1" />
                <el-option label="焊工标准科目模板" value="2" />
                <el-option label="通用理论科目模板" value="3" />
                <el-option label="通用实操科目模板" value="4" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="应用等级" prop="skillLevels">
              <el-checkbox-group v-model="batchForm.skillLevels">
                <el-checkbox :label="1">初级</el-checkbox>
                <el-checkbox :label="2">中级</el-checkbox>
                <el-checkbox :label="3">高级</el-checkbox>
                <el-checkbox :label="4">技师</el-checkbox>
                <el-checkbox :label="5">高级技师</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <!-- 模板预览 -->
            <div v-if="templatePreview.length > 0">
              <el-divider content-position="left">模板预览</el-divider>
              <el-table :data="templatePreview" border style="width: 100%" max-height="300">
                <el-table-column prop="subjectName" label="科目名称" />
                <el-table-column prop="subjectType" label="科目类型">
                  <template #default="{ row }">
                    <el-tag>{{ getSubjectTypeName(row.subjectType) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="examTime" label="考试时长" />
                <el-table-column prop="totalScore" label="总分" />
                <el-table-column prop="passScore" label="及格分" />
              </el-table>
            </div>
          </div>
          
          <!-- Excel导入 -->
          <div v-if="batchForm.createMethod === 'import'">
            <el-divider content-position="left">Excel导入</el-divider>
            <el-form-item label="选择文件" prop="importFile">
              <el-upload
                ref="uploadRef"
                :limit="1"
                :auto-upload="false"
                :on-change="handleFileChange"
                :before-remove="beforeFileRemove"
                accept=".xlsx,.xls"
              >
                <el-button type="primary">选择Excel文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传xlsx/xls文件，且不超过10MB
                    <el-link type="primary" @click="downloadTemplate" style="margin-left: 10px;">
                      下载导入模板
                    </el-link>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            
            <!-- 导入预览 -->
            <div v-if="importPreview.length > 0">
              <el-divider content-position="left">导入预览</el-divider>
              <el-alert
                :title="`共解析到 ${importPreview.length} 条科目数据，其中 ${validCount} 条有效，${errorCount} 条错误`"
                type="info"
                :closable="false"
                style="margin-bottom: 10px;"
              />
              <el-table :data="importPreview" border style="width: 100%" max-height="300">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="subjectName" label="科目名称" />
                <el-table-column prop="subjectType" label="科目类型" />
                <el-table-column prop="examTime" label="考试时长" />
                <el-table-column prop="totalScore" label="总分" />
                <el-table-column prop="passScore" label="及格分" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.isValid ? 'success' : 'danger'">
                      {{ row.isValid ? '有效' : '错误' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="errorMessage" label="错误信息" />
              </el-table>
            </div>
          </div>
          
          <!-- 手动创建 -->
          <div v-if="batchForm.createMethod === 'manual'">
            <el-divider content-position="left">手动配置</el-divider>
            <el-form-item label="科目数量" prop="subjectCount">
              <el-input-number
                v-model="batchForm.subjectCount"
                :min="1"
                :max="20"
                @change="generateManualSubjects"
              />
            </el-form-item>
            
            <!-- 手动科目列表 -->
            <div v-if="manualSubjects.length > 0" style="margin-top: 20px;">
              <el-divider content-position="left">科目配置</el-divider>
              <div v-for="(subject, index) in manualSubjects" :key="index" style="margin-bottom: 20px;">
                <el-card>
                  <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                      <span>科目 {{ index + 1 }}</span>
                      <el-button
                        type="danger"
                        size="small"
                        @click="removeManualSubject(index)"
                        v-if="manualSubjects.length > 1"
                      >
                        删除
                      </el-button>
                    </div>
                  </template>
                  
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item :label="`科目名称`">
                        <el-input v-model="subject.subjectName" placeholder="请输入科目名称" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item :label="`科目类型`">
                        <el-select v-model="subject.subjectType" placeholder="请选择科目类型">
                          <el-option label="理论考试" value="theory" />
                          <el-option label="实操考试" value="practice" />
                          <el-option label="综合考试" value="comprehensive" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item :label="`考试时长(分钟)`">
                        <el-input-number
                          v-model="subject.examTime"
                          :min="30"
                          :max="480"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="`总分`">
                        <el-input-number
                          v-model="subject.totalScore"
                          :min="50"
                          :max="200"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="`及格分`">
                        <el-input-number
                          v-model="subject.passScore"
                          :min="30"
                          :max="subject.totalScore"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-form-item :label="`科目描述`">
                    <el-input
                      v-model="subject.description"
                      type="textarea"
                      :rows="2"
                      placeholder="请输入科目描述"
                    />
                  </el-form-item>
                </el-card>
              </div>
              
              <el-button type="dashed" @click="addManualSubject" style="width: 100%;">
                + 添加科目
              </el-button>
            </div>
          </div>
        </el-form>
      </el-tab-pane>
      
      <!-- 创建结果 -->
      <el-tab-pane label="创建结果" name="result" :disabled="!hasCreateResult">
        <el-result
          :icon="createResult.success ? 'success' : 'error'"
          :title="createResult.success ? '批量创建成功' : '批量创建失败'"
          :sub-title="createResult.message"
        />
        
        <div v-if="createResult.details && createResult.details.length > 0">
          <el-divider content-position="left">详细结果</el-divider>
          <el-table :data="createResult.details" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="subjectName" label="科目名称" />
            <el-table-column prop="status" label="创建状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.success ? 'success' : 'danger'">
                  {{ row.success ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="结果信息" />
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <template #footer>
      <el-space>
        <el-button @click="createSubjects" type="primary" :loading="formLoading" v-if="activeTab === 'batch'">
          开始创建
        </el-button>
        <el-button @click="resetForm" v-if="activeTab === 'batch'">
          重置
        </el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </el-space>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const activeTab = ref('batch')
const batchFormRef = ref()
const uploadRef = ref()

const batchForm = ref({
  createMethod: 'template',
  professionId: '',
  templateId: '',
  skillLevels: [] as number[],
  importFile: null,
  subjectCount: 3
})

const batchRules = ref({
  createMethod: [{ required: true, message: '请选择创建方式', trigger: 'change' }],
  professionId: [{ required: true, message: '请选择目标职业', trigger: 'change' }],
  templateId: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (batchForm.value.createMethod === 'template' && !value) {
          callback(new Error('请选择科目模板'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  skillLevels: [
    {
      validator: (rule: any, value: number[], callback: Function) => {
        if (batchForm.value.createMethod === 'template' && (!value || value.length === 0)) {
          callback(new Error('请至少选择一个应用等级'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

const templatePreview = ref([])
const importPreview = ref([])
const manualSubjects = ref([])
const createResult = ref({
  success: false,
  message: '',
  details: []
})
const hasCreateResult = ref(false)

const validCount = computed(() => importPreview.value.filter(item => item.isValid).length)
const errorCount = computed(() => importPreview.value.filter(item => !item.isValid).length)

const getSubjectTypeName = (type: string) => {
  const typeMap = {
    'theory': '理论考试',
    'practice': '实操考试',
    'comprehensive': '综合考试'
  }
  return typeMap[type] || type
}

const loadTemplate = () => {
  if (!batchForm.value.templateId) return
  
  // 模拟加载模板数据
  templatePreview.value = [
    {
      subjectName: '电工基础理论',
      subjectType: 'theory',
      examTime: 120,
      totalScore: 100,
      passScore: 60
    },
    {
      subjectName: '电工实操技能',
      subjectType: 'practice',
      examTime: 180,
      totalScore: 100,
      passScore: 60
    }
  ]
}

const handleFileChange = (file: any) => {
  batchForm.value.importFile = file.raw
  // 模拟解析Excel文件
  setTimeout(() => {
    importPreview.value = [
      {
        subjectName: '电工理论基础',
        subjectType: 'theory',
        examTime: 120,
        totalScore: 100,
        passScore: 60,
        isValid: true,
        errorMessage: ''
      },
      {
        subjectName: '电工实操',
        subjectType: 'practice',
        examTime: 180,
        totalScore: 100,
        passScore: 60,
        isValid: true,
        errorMessage: ''
      },
      {
        subjectName: '',
        subjectType: 'theory',
        examTime: 90,
        totalScore: 100,
        passScore: 60,
        isValid: false,
        errorMessage: '科目名称不能为空'
      }
    ]
  }, 1000)
}

const beforeFileRemove = () => {
  importPreview.value = []
  return true
}

const downloadTemplate = () => {
  // TODO: 下载导入模板
  ElMessage.info('模板下载功能开发中...')
}

const generateManualSubjects = () => {
  const count = batchForm.value.subjectCount
  manualSubjects.value = []
  
  for (let i = 0; i < count; i++) {
    manualSubjects.value.push({
      subjectName: '',
      subjectType: 'theory',
      examTime: 120,
      totalScore: 100,
      passScore: 60,
      description: ''
    })
  }
}

const addManualSubject = () => {
  manualSubjects.value.push({
    subjectName: '',
    subjectType: 'theory',
    examTime: 120,
    totalScore: 100,
    passScore: 60,
    description: ''
  })
  batchForm.value.subjectCount = manualSubjects.value.length
}

const removeManualSubject = (index: number) => {
  manualSubjects.value.splice(index, 1)
  batchForm.value.subjectCount = manualSubjects.value.length
}

const createSubjects = async () => {
  const elForm = batchFormRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  // 验证具体数据
  if (batchForm.value.createMethod === 'import' && importPreview.value.length === 0) {
    ElMessage.warning('请先选择并解析Excel文件')
    return
  }
  
  if (batchForm.value.createMethod === 'manual' && manualSubjects.value.some(s => !s.subjectName)) {
    ElMessage.warning('请完善所有科目的名称')
    return
  }
  
  formLoading.value = true
  try {
    let createData = []
    
    switch (batchForm.value.createMethod) {
      case 'template':
        // 基于模板创建
        createData = templatePreview.value.map(template => ({
          ...template,
          professionId: batchForm.value.professionId,
          skillLevels: batchForm.value.skillLevels
        }))
        break
      case 'import':
        // 基于导入创建
        createData = importPreview.value.filter(item => item.isValid)
        break
      case 'manual':
        // 手动创建
        createData = manualSubjects.value.filter(s => s.subjectName)
        break
    }
    
    // TODO: 调用后端API创建科目
    console.log('批量创建科目:', createData)
    
    // 模拟创建结果
    createResult.value = {
      success: true,
      message: `成功创建 ${createData.length} 个科目`,
      details: createData.map(item => ({
        subjectName: item.subjectName,
        success: true,
        message: '创建成功'
      }))
    }
    
    hasCreateResult.value = true
    activeTab.value = 'result'
    
    emit('success')
    ElMessage.success('批量创建成功')
  } catch (error) {
    createResult.value = {
      success: false,
      message: '批量创建失败',
      details: []
    }
    hasCreateResult.value = true
    activeTab.value = 'result'
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  batchForm.value = {
    createMethod: 'template',
    professionId: '',
    templateId: '',
    skillLevels: [],
    importFile: null,
    subjectCount: 3
  }
  
  templatePreview.value = []
  importPreview.value = []
  manualSubjects.value = []
  createResult.value = { success: false, message: '', details: [] }
  hasCreateResult.value = false
  activeTab.value = 'batch'
  
  if (batchFormRef.value) {
    batchFormRef.value.clearValidate()
  }
  
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

defineExpose({ open })
</script> 